package swingExtended.inputBrowsePanel;

import java.io.File;
import javax.swing.JFileChooser;
import swingExtended.SwingExtended;

/**
 *
 * @author Shimu
 */
public class InputBrowserPanel extends javax.swing.JPanel {

    private InputBrowsePanelListener textListener =
            new InputBrowsePanelListener() {

                @Override
                public void fileChanged(File newFile) {
                }
            };
    
    private final JFileChooser FILE_CHOOSER;
    private String input = "";
    private boolean checkFileExist;

    public InputBrowserPanel() {
        this("Input File:");
    }

    public InputBrowserPanel(String labelText) {
        this(labelText, "Browse");
    }

    /** Creates new form InputBrowserPanel */
    public InputBrowserPanel(String labelText, String buttonText) {
        initComponents();

        this.FILE_CHOOSER = new JFileChooser();

        this.labelInput.setText(labelText);
        this.buttonBrowse.setText(buttonText);
        this.checkFileExist(true);
    }

    public final void checkFileExist(boolean checkFileExist) {
        this.checkFileExist = checkFileExist;
    }

    public void setListener(InputBrowsePanelListener listener) {
        this.textListener = listener;
        this.textFieldInputActionPerformed(null);
    }

    /**
     * Disables the children as well.
     * 
     * @param enabled 
     */
    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        this.labelInput.setEnabled(enabled);
        this.textFieldInput.setEnabled(enabled);
        this.buttonBrowse.setEnabled(enabled);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        labelInput = new javax.swing.JLabel();
        textFieldInput = new javax.swing.JTextField();
        buttonBrowse = new javax.swing.JButton();

        labelInput.setText("Input Name:");

        textFieldInput.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textFieldInputActionPerformed(evt);
            }
        });

        buttonBrowse.setText("Browse");
        buttonBrowse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonBrowseActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(labelInput)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(textFieldInput, javax.swing.GroupLayout.DEFAULT_SIZE, 243, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonBrowse))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(labelInput)
                .addComponent(textFieldInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(buttonBrowse))
        );
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Checks if the given file exists. If not, opens a warning window then
     * returns false. Otherwise, returns true.
     * 
     * @param file
     * @return 
     */
    private boolean validateFile(File file) {
        if (file == null) {
            SwingExtended.openWarningWindow(this,
                    "No file or directory selected!");
            return false;

        } else if (checkFileExist && !file.exists()) {
            final String errorMsg = String.format(
                    "File or directory: %s does not exist!",
                    file.getAbsolutePath());
            SwingExtended.openWarningWindow(this, errorMsg);
            return false;

        } else {
            return true;
        }
    }

    /**
     * Notify the textListener of a file change.
     * @param file the new file
     */
    private void notifyListener(File file) {
        // Validate the file before notifying the text listener
        if (validateFile(file)) {
            this.textListener.fileChanged(file);
        }
    }

    public File getFile() {
        return new File(textFieldInput.getText());
    }

    private void textFieldInputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textFieldInputActionPerformed
        String temp = this.textFieldInput.getText();
        if (input.equals(temp)) {
            // do nothing, input String did not change
            return;
        }
        this.input = temp;
        notifyListener(new File(this.input));
    }//GEN-LAST:event_textFieldInputActionPerformed

    private void buttonBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonBrowseActionPerformed
        this.FILE_CHOOSER.setCurrentDirectory(
                    new File(this.textFieldInput.getText()));
        this.FILE_CHOOSER.showOpenDialog(this);
        File file = this.FILE_CHOOSER.getSelectedFile();
        if (file != null) {
            this.textFieldInput.setText(file.getAbsolutePath());
            notifyListener(file);
        }
    }//GEN-LAST:event_buttonBrowseActionPerformed

    /**
     * Returns the file chooser used by this InputBrowsePanel so the user can
     * customize the FILE_CHOOSER by changing its fields.
     * 
     * @return the file chooser used by this InputBrowsePanel
     */
    public JFileChooser getFileChooser() {
        return this.FILE_CHOOSER;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonBrowse;
    private javax.swing.JLabel labelInput;
    private javax.swing.JTextField textFieldInput;
    // End of variables declaration//GEN-END:variables

    public String getText() {
        return textFieldInput.getText();
    }

    public void setText(String value) {
        textFieldInput.setText(value);
    }
}
